/* Copyright (c) 2021, National University of Defense Technology. All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *     http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include <stdio.h>
#include "coo_io.h"

namespace YHAMG
{

void COO_Read(const char* filename, COO_Matrix& A)
{
	FILE* f = fopen(filename, "r");

	int n, m, nz;

	fscanf(f, "%d %d %d", &n, &m, &nz);

	int* Ai = new int[nz];
	int* Aj = new int[nz];
	double* Av = new double[nz];

	for (int i = 0; i < nz; ++i)
	{
		fscanf(f, "\n%d %d %lg", &Ai[i], &Aj[i], &Av[i]);
		--Ai[i];
		--Aj[i];
	}

	fclose(f);

	A.Free();
	A.size[0] = n;
	A.size[1] = m;
	A.nnz = nz;
	A.rowind = Ai;
	A.colind = Aj;
	A.values = Av;
}

void COO_Write(const char* filename, const COO_Matrix& A)
{
	int n = A.size[0];
	int m = A.size[1];
	int nz = A.nnz;

	int* Ai = A.rowind;
	int* Aj = A.colind;
	double* Av = A.values;

	FILE* f = fopen(filename, "w");

	fprintf(f, "%d %d %d", n, m, nz);

	for (int i = 0; i < nz; ++i)
		fprintf(f, "\n%d %d %20.16g", Ai[i] + 1, Aj[i] + 1, Av[i]);

	fclose(f);
}

}